var fieldOffset = 30;
var goalSize = {
    x: fieldOffset,
    y: 150
};
const canvasWidth = 800, canvasHeight = 600;

var score = '0 - 0';
const log = console.log;
const socket = io('http://localhost:8081/');
let users = [];

let user;
let x;
let goal = {x: 30, y: 150};
let blueScore = 0;
let redScore = 0;
var username = 'Unnamed';
var speed = 3;
var userR = 20;
var ballR = 12;
var pink = '#C80064'; //200, 0, 100;
var teal = '#74C2E1'; //116, 194, 225;
var ballLoc;

function addParticipantsMessage(data) {
    var message = '';
    if (data.numUsers === 1) {
        message += "Now there's 1 participant";
    } else {
        message += "Now there are " + data.numUsers + " participants";
    }
    log(message);
}


document.getElementById('login').addEventListener('click', function () {
    let username = document.getElementById('name').value, team = 'red';
    if (username && team) {
        user = {username: username, password: '123', team: team, id: socket.id, x: 100, y: 200, isKicking: false};
        document.getElementById('popup').style.display = 'none';
        socket.emit('onLoad', user);
        socket.on('onLoad', function (data) {
            let teams = data.teams, _users = data.users;
            score = `${teams.red.score} - ${teams.blue.score}`;
            users = _users;
            log(data);
        })
        loop();
    } else {
    }

});

socket.on('connect', function () {
    log('connect success')
    connected = true;
});
socket.on('disconnect', function () {
    log('connect failed')
    document.getElementById('popup').style.display = 'flex'
    connected = false;
});

// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
});

function preload() {


    socket.on('scored', function (teams) {
        //        console.log(scores);
        score = `${teams.red.score} - ${teams.blue.score}`;

    });
}

function setup() {
    createCanvas(canvasWidth, canvasHeight);
    // Only start looping when you have the initial data from the server
    noLoop();
}

function draw() {
    background('#2980b9');
    drawField();
    drawScore();

    if (user) { // To avoid errors on first drawing
        moveUser();
        userBoundaries();
        socket.emit('tick', user);
        socket.on('tick', function (data) {
            users = data.users;
            ballLoc = data.ballLoc;

        });
        drawUser(user);
    }

    drawAllUsersExceptThis();

    if (ballLoc)
        drawTheBall(ballLoc);
}

function drawTheBall(_ballLoc) {
    fill(255);
    stroke(0);
    ellipse(_ballLoc.x, _ballLoc.y, ballR * 2);
}

function drawUser(_user) {

    // Drawing the username;
    textAlign(CENTER);
    textSize(14);
    fill(255);
    strokeWeight(0);
    text(`${_user.username}`, _user.x, _user.y - userR * 1.5);

    if (_user.team === 'red') {
        fill(pink)
    } else {
        fill(teal);
    }

    if (_user.isKicking) {
        stroke(255);
    } else {
        stroke(0);
    }

    strokeWeight(3);
    ellipse(_user.x, _user.y, userR * 2);
}

function userBoundaries() {
    // Right
    if (user.x + userR > width - fieldOffset) {
        user.x = width - userR - fieldOffset;

        // Left
    } else if (user.x - userR < fieldOffset) {
        user.x = userR + fieldOffset;
    }

    // Bottom
    if (user.y + userR > height - 3) {
        user.y = height - userR - 3;

        // Top
    } else if (user.y - userR < 3) {
        user.y = userR + 3;
    }
}

function drawAllUsersExceptThis() {

    for (let i in users) {
        if (socket.id !== i&&users.hasOwnProperty(i)) {
            drawUser(users[i]);
        }
    }
    // users.forEach(user => {
    //     if (user.id !== socket.id) {
    //         drawUser(user);
    //     }
    // });
}

function moveUser() {
    if (keyIsDown(LEFT_ARROW))
        user.x -= speed;

    if (keyIsDown(RIGHT_ARROW))
        user.x += speed;

    if (keyIsDown(UP_ARROW))
        user.y -= speed;

    if (keyIsDown(DOWN_ARROW))
        user.y += speed;
}

function keyPressed() {

    // 32 is the keyCode for the 'space' button
    if (keyCode === 32) {
        user.isKicking = true;
    }
}

function keyReleased() {

    // 32 is the keyCode for the 'space' button
    if (keyCode === 32) {
        user.isKicking = false;
    }
}

function drawField() {
    // Draw field margins
    fill('#00680A');
    strokeWeight(6);
    stroke(255);
    rect(fieldOffset, 3, width - fieldOffset * 2, height - 6);

    // Draw middle line
    strokeWeight(6);
    line(width / 2, 0, width / 2, height);

    // Draw middle cercle
    ellipse(width / 2, height / 2, 100, 100);

    // Draw middle point
    fill(255);
    ellipse(width / 2, height / 2, 10, 10);

    // Drawing the 2 goals
    stroke(255);

    // Left goal
    fill(pink);
    rect(3, height / 2 - goalSize.y / 2, goalSize.x - 3, goalSize.y);

    // Right goal
    fill(teal);
    rect(width - goalSize.x, height / 2 - goalSize.y / 2, goalSize.x - 3, goalSize.y);
}

function drawScore() {
    fill(255);
    strokeWeight(0);
    textAlign(LEFT);
    textSize(16);
    text('Red - Blue', 40, 30);
    text(score, 63, 50);
}

